﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SURLService
{
    class JobManager<T> where T : IJob
    {
        //private SemaphoreSlim _slavesQuota;
        private SemaphoreSlim _queueQuota;

        private JobQueue<T> _queue;

        public JobManager(int numberOfSlaves)
        {
            //_slavesQuota = new SemaphoreSlim(numberOfSlaves);
            _queue = new JobQueue<T>();

            for (int i = 0; i < numberOfSlaves; ++i)
            {
                ThreadPool.QueueUserWorkItem(StartJob);
            }
            _queueQuota = new SemaphoreSlim(0);
        }

        public void Add(T t)
        {
            _queue.Enqueue(t);
            Console.WriteLine("Job Queue Length {0}", _queue.Length());
            _queueQuota.Release();
        }

        private void StartJob(object state)
        {
            while (true)
            {
                //_slavesQuota.Wait();
                _queueQuota.Wait();
                T job = _queue.Dequeue();
                Console.WriteLine("Job Queue Length {0}", _queue.Length());
                job.Run();
                //_slavesQuota.Release();
            }
        }
    }
}
